package com.xsomnus.network_programming.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.buffer.UnpooledDirectByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * @author 叶小夏
 * @since 2019-08-21 16:24
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello, Server!", StandardCharsets.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf responseMsg = (ByteBuf) msg;
        System.out.println("(1)responseMsg refCnt = " + responseMsg.refCnt());
        byte[] bytes = new byte[responseMsg.readableBytes()];
        responseMsg.readBytes(bytes);
        String str = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("(2)responseMsg refCnt = " + responseMsg.refCnt() + " receive: " + str);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
